<template>
  <a-modal
    destroyOnClose
    :visible="visible"
    :title="title"
    @update:visible="update"
    @ok="ok"
  >
    <a-tree
      checkable
      :tree-data="menuTree"
      v-model:checkedKeys="checkedKeys"
      :fieldNames="{
        children: 'children',
        title: 'display_name',
        key: 'id',
      }"
      @check="check"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRefs, defineEmits, watch, onMounted } from "vue";
import { menuApi } from "@/api/menu";
import { roleApi } from "@/api/role";
import { eachTreeData } from "@/utils";
import { ReloadOutlined } from "@ant-design/icons-vue";
const emits = defineEmits(["update:visible", "reload"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tempData: {
    default: {},
  },
});
const { visible, tempData } = toRefs(props);
const title = ref("提示");
const menuTree = ref([]);
const form = ref({});
const checkedKeys = ref([]);
const menuIds = ref([]);

watch(visible, (e) => {
  checkedKeys.value = []
  menuIds.value = []

  if (!e) return;
  const { id } = tempData.value;
  if (id) title.value = "修改授权";
  else title.value = "新增授权";
  form.value = tempData.value;
  
  getMenu();
  getRoleMenu();
});

function update(e) {
  emits("update:visible", e);
}
async function ok() {
  const { id: role_id } = form.value;
  const system_menu_ids = menuIds.value;

  if (!system_menu_ids.length) {
    emits("update:visible", false);
    return;
  }
  await roleApi.authMenuEdit({
    role_id,
    system_menu_ids,
  });
  emits("update:visible", false);
  emits("reload");
}
function check(checkedKeys, e) {
  const { halfCheckedKeys } = e;
  menuIds.value = [...checkedKeys, ...halfCheckedKeys];
}
function getMenu() {
  menuApi.page().then((res) => {
    menuTree.value = res.list;
  });
}
function getRoleMenu() {
  const { id } = form.value;
  roleApi
    .authMenu({
      id,
    })
    .then((res) => {
      const { system_menu_ids } = res;
      // 处理数据
      eachTreeData(menuTree.value, (item, index, parent) => {
        const { id, type, children } = item;
        if (system_menu_ids.includes(id)) {
          if (item.children) return;
          checkedKeys.value.push(id);
        }
      });
    });
}
</script>

<style lang="less" scoped></style>
